package com.zll.onlineExam.activities;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.LayoutInflaterCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.mikepenz.iconics.context.IconicsLayoutInflater2;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.zll.onlineExam.R;
import com.zll.onlineExam.adapter.QuestionItemViewAdapter;
import com.zll.onlineExam.adapter.holder.QuestionItemViewHolder;
import com.zll.onlineExam.ajax.Ajax;
import com.zll.onlineExam.ajax.HTTPConfig;
import com.zll.onlineExam.ajax.ReqCallback;
import com.zll.onlineExam.entity.ServiceConstant;
import com.zll.onlineExam.entity.out.PaperDtoOut;
import com.zll.onlineExam.entity.out.QuestionDtoOut;
import com.zll.onlineExam.utils.GlobalDataHolder;
import com.zll.onlineExam.utils.StringUtil;
import com.zll.onlineExam.utils.XToastUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DoExamActivity extends AppCompatActivity implements View.OnClickListener {

    private ImageView mBack;
    private ImageView mCommit;
    private TextView mTitle;
    private TextView mCountDown;
    private static RecyclerView mRecycleView;
    private static Handler mHandler;
    private Map<String, Object> parmas;
    private boolean testMode;

    private final int FETCH_SUCCESS = 1;
    private final int FETCH_FAIL = 0;
    private final int FETCH_ERROR = -1;
    private final int COMMIT_SUCCESS = 4;
    private final int COMMIT_FAIL = 3;
    private final int COMMIT_ERROR = 2;

    private static long beginTime;

    private static DataHolder mHolder;
    private static QuestionItemViewAdapter mAdapter;
    private static CountDownTimer timer;

    private static final String TAG = "===DoExamActivity";

    private class DataHolder {
        private PaperDtoOut data;

        public PaperDtoOut getData() {
            return data;
        }

        public DataHolder setData(PaperDtoOut data) {
            this.data = data;
            return this;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        LayoutInflaterCompat.setFactory2(getLayoutInflater(), new IconicsLayoutInflater2(getDelegate()));
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_do_exam);
        parmas = new HashMap<>();

        initView();
        initListener();
        initHandler();
        initData();
    }

    private void initHandler() {
        mHandler = new Handler() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                mCommit.setEnabled(true);
                switch (msg.what) {
                    case FETCH_SUCCESS:
                        mTitle.setText(mHolder.getData().getTitle());
                        mAdapter.setData(mHolder.getData().getQuestions());
                        if (StringUtil.isBlank(mHolder.getData().getUserTotalScore())) {
                            // 未做过的试卷
                            LocalDate expire = LocalDate.parse(mHolder.getData().getExpireTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                            if (expire.isBefore(LocalDate.now())){
                                // 过期的，不能提交，显示已过期
                                mCommit.setVisibility(View.INVISIBLE);
                                mCountDown.setText("该测试已过期");
                            }else{
                                // 正常进入测试状态
                                testMode = true;
                                mCommit.setVisibility(View.VISIBLE);
                                initTimer(mHolder.getData());
                            }
                        }else{
                            // 做过的试卷
                            testMode = false;
                            mCommit.setVisibility(View.INVISIBLE);
                            mCountDown.setText("用时 "+mHolder.getData().getUserCostTime()+" 分钟");
                        }
                        break;
                    case COMMIT_SUCCESS:
                        XToastUtils.success("提交成功");
                        finish();
                        break;
                    case FETCH_FAIL:
                        XToastUtils.error("获取失败");
                        break;
                    case FETCH_ERROR:
                        XToastUtils.error("网络异常");
                        break;
                    case COMMIT_FAIL:
                        XToastUtils.error("提交失败");
                        break;
                    case COMMIT_ERROR:
                        XToastUtils.error("网络异常");
                        break;
                    default:
                        break;
                }

            }
        };
    }

    private void initView() {
        mBack = findViewById(R.id.iv_back);
        mCommit = findViewById(R.id.iv_commit);
        mTitle = findViewById(R.id.a_de_title);
        mCountDown = findViewById(R.id.tv_count_down);
        mRecycleView = findViewById(R.id.recyclerView);

        mRecycleView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new QuestionItemViewAdapter(new ArrayList<>());
        mRecycleView.setAdapter(mAdapter);

    }

    private void initListener() {
        mBack.setOnClickListener(this);
        mCommit.setOnClickListener(this);
    }

    private void initData() {
        mHolder = new DataHolder();
        String pid = getIntent().getStringExtra("pid");
        parmas.put("pid", pid);
        parmas.put("uid", GlobalDataHolder.getInstance().getCurUser().getUid());
        Ajax.post(HTTPConfig.LIST_PAPER_QUESTION, parmas, new ReqCallback() {
            @Override
            public void onSuccess(JSONObject resp) {
                PaperDtoOut dto = resp.getJSONObject("data").toJavaObject(PaperDtoOut.class);
                mHolder.setData(dto);
                mHandler.sendEmptyMessage(FETCH_SUCCESS);
            }

            @Override
            public void onFail(String msg) {
                mHandler.sendEmptyMessage(FETCH_FAIL);
            }

            @Override
            public void onError(String msg) {
                mHandler.sendEmptyMessage(FETCH_ERROR);
            }
        });
    }

    private void initTimer(PaperDtoOut paperDtoOut){
        beginTime = System.currentTimeMillis();
        if ("不限时".equals(paperDtoOut.getDuration())){
            mCountDown.setText("不限时");
            return;
        }
        long totalSeconds = Long.parseLong(paperDtoOut.getDuration())*1000*60;

        timer = new CountDownTimer(totalSeconds,1000) {
            @Override
            public void onTick(long l) {
                long min = l/1000/60;
                long sec = (l/1000)%60;
                if (sec < 10){
                    mCountDown.setText("倒计时 "+min+":0"+sec);
                }else {
                    mCountDown.setText("倒计时 " + min + ":" + sec);
                }
                if (l/1000==30){
                    // 30秒提示交卷
                    new MaterialDialog.Builder(DoExamActivity.this)
                            .content("还有30秒结束考试，将自动提交")
                            .positiveText("确定")
                            .show();
                }
            }

            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onFinish() {
                checkAndSendData();
            }
        };
        timer.start();
    }

    private void doCommit(Map<String,Object> map){
        Ajax.post(HTTPConfig.COMMIT_EXAM, map, new ReqCallback() {
            @Override
            public void onSuccess(JSONObject resp) {
                mHandler.sendEmptyMessage(COMMIT_SUCCESS);
            }

            @Override
            public void onFail(String msg) {
                mHandler.sendEmptyMessage(COMMIT_FAIL);
            }

            @Override
            public void onError(String msg) {
                mHandler.sendEmptyMessage(COMMIT_ERROR);
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void checkAndSendData() {
        XToastUtils.info("正在提交，请稍候");
        mCommit.setEnabled(false);

        long endTime = System.currentTimeMillis();
        List<QuestionItemViewHolder> holders = mAdapter.getHolders();
        List<QuestionDtoOut> questions = mHolder.getData().getQuestions();
        Map<String, Object> map = new HashMap<>();
        String pid = getIntent().getStringExtra("pid");
        map.put("pid", pid);
        map.put("uid", GlobalDataHolder.getInstance().getCurUser().getUid());
        map.put("costTime", String.valueOf((endTime-beginTime)/60000));

        boolean finished = true;
        List<Map<String, Object>> answers = new ArrayList<>();
        for (int i = 0 ;i< questions.size();i++){
            Map<String,Object> line = new HashMap<>();
            QuestionDtoOut dto = questions.get(i);
            QuestionItemViewHolder holder = holders.get(i);
            line.put("qid",dto.getQid());
            if (ServiceConstant.MULTI.equals(dto.getType())){
                // 多选
                List<String> strs = new ArrayList<>();
                if (holder.mC1.isChecked()){
                    strs.add("A");
                }
                if (holder.mC2.isChecked()){
                    strs.add("B");
                }
                if (holder.mC3.isChecked()){
                    strs.add("C");
                }
                if (holder.mC4.isChecked()){
                    strs.add("D");
                }
                if (strs.size() == 0){
                    finished = false;
                    line.put("answer", "");
                }else{
                    line.put("answer", String.join(",",strs));
                }
            }
            if (ServiceConstant.SINGLE.equals(dto.getType())){
                // 单选
                String str = "";
                if (holder.mRD1.isChecked()){
                    str="A";
                }
                if (holder.mRD2.isChecked()){
                    str="B";
                }
                if (holder.mRD3.isChecked()){
                    str="C";
                }
                if (holder.mRD4.isChecked()){
                    str="D";
                }
                if (StringUtil.isBlank(str)){
                    finished = false;
                    line.put("answer", "");
                }else{
                    line.put("answer", str);
                }
            }
            if (ServiceConstant.CHOOSE.equals(dto.getType())){
                // 判断
                String str = "";
                if (holder.mRDt.isChecked()){
                    str="A";
                }
                if (holder.mRDf.isChecked()){
                    str="B";
                }
                if (StringUtil.isBlank(str)){
                    finished = false;
                    line.put("answer", "");
                }else{
                    line.put("answer", str);
                }
            }
            if (ServiceConstant.FILL.equals(dto.getType())) {
                // 填空
                if (StringUtil.isNotBlank(holder.mTextInput.getEditValue())){
                    line.put("answer", holder.mTextInput.getEditValue());
                }else{
                    finished = false;
                    line.put("answer", "");
                }
            }
            answers.add(line);
        }

        map.put("userAnswers",answers);
        if (!finished){
            new MaterialDialog.Builder(this)
                    .content("还有题目没做完，确定提交吗？")
                    .positiveText("确定")
                    .negativeText("取消")
                    .onPositive((a,b)->doCommit(map))
                    .show();
        }else{
            doCommit(map);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_back) {
            checkAndBack();
        }
        if (id == R.id.iv_commit) {
            checkAndSendData();
        }
    }

    private void checkAndBack(){
        if (testMode){
            new MaterialDialog.Builder(this)
                    .content("没有完成测试，确定退出吗？")
                    .positiveText("确定")
                    .negativeText("取消")
                    .onPositive((a,b)->cleanAndFinish())
                    .show();
        }else{
            cleanAndFinish();
        }
    }

    private void cleanAndFinish(){
        if (timer != null){
            timer.cancel();
            Log.d(TAG, "cleanAndFinish: timer 已清空");
        }
        finish();
    }

    /**
     * 菜单、返回键响应
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            checkAndBack();
        }
        return true;
    }
}